package cc.siyecao.fastdfs.command.tracker;

import cc.siyecao.fastdfs.model.RecvPackageInfo;
import cc.siyecao.fastdfs.protocol.GroupProtocol;
import cc.siyecao.fastdfs.protocol.ProtocolDecoder;
import cc.siyecao.fastdfs.util.ProtocolUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

/**
 * 列出组命令
 *
 * @author lyt
 */
public class ListGroupsCommand extends FdfsTrackerCommand<List<GroupProtocol>> {


    @Override
    protected void send(OutputStream out, Charset charset) throws Exception {
        byte[] header = ProtocolUtil.packHeader( TRACKER_PROTO_CMD_SERVER_LIST_GROUP, 0, (byte) 0 );
        out.write( header );
    }

    @Override
    protected List<GroupProtocol> receive(InputStream in, Charset charset) throws Exception {
        RecvPackageInfo pkgInfo = ProtocolUtil.recvPackage( in, TRACKER_PROTO_CMD_RESP, -1 );
        this.errno = pkgInfo.errno;
        if (pkgInfo.errno != 0) {
            return null;
        }

        ProtocolDecoder<GroupProtocol> decoder = new ProtocolDecoder<GroupProtocol>();
        GroupProtocol[] groupProtocols = decoder.decode( pkgInfo.body, GroupProtocol.class, GroupProtocol.getFieldsTotalSize() );
        return Arrays.asList( groupProtocols );
    }
}
